<template>
	<div class="app-container">
		<el-form :model="data.info" :inline="true" class="w-full" label-width="120">
			<el-collapse v-model="data.activeOperations">
				<!-- 基础信息 -->
				<el-collapse-item :name="1" class="info1">
					<template #title>
						<div class="h-8 text-base pl-4 mt-2 font-semibold relative text-[#fafafa]">
							{{ $t('machine.addMachine.basic') }}</div>
					</template>
					<template #default>
						<div>
							<machinetop :info="data.info" @onstatus="getSingle" :flag="'operations'" />
						</div>
					</template>
				</el-collapse-item>
				<!-- 状态信息 -->
				<el-collapse-item :name="2" class="info2 mt-4">
					<template #title>
						<div class="h-8 text-base pl-4 mt-2 font-semibold relative text-[#fafafa]">
							{{ $t('machine.operations.statusInfo') }}</div>
					</template>
					<template #default>
						<div class="grid grid-cols-3 gap-10">
							<div class="h-64 status_item p-3" v-for="(items, index) in elFormData.statusList"
								:key="index">
								<h1 class="text-base font-bold">{{ items.title }}</h1>
								<div class="mt-2 w-full flex flex-wrap">
									<el-table :data="items.list" :key="items.list.me_id"
										:header-cell-style="{ 'text-align': 'center' }" border height="200"
										:cell-style="{ 'text-align': 'center' }" class="w-full">
										<el-table-column prop="errorCode" :label="$t('machine.operations.error')">
											<template #default="scope">
												<span class="text-title  cursor-pointer"
													@click="onErrorCode(scope.row)">{{ scope.row.errorCode || '--'
													}}</span>
											</template>
										</el-table-column>
										<el-table-column prop="errorCode" :label="$t('date.uploaded')">
											<template #default="scope">
												<span>{{ getPlevel.gettime(scope.row.create_time, 3) }}</span>
											</template>
										</el-table-column>
										<el-table-column prop="remark" :label="$t('machine.operations.notes')">
											<template #default="scope">
												{{ scope.row.remark || '--' }}
											</template>
										</el-table-column>
										<el-table-column prop="remark" :label="$t('machine.operations.ifHandle')">
											<template #default="scope">
												<span v-if="scope.row.errorCode == '1200000'"
													@click="previewVideo(scope.row.create_time, scope.row.me_id)"
													class="border p-1  bg-[#eee] cursor-pointer text-title "> {{
														$t('source.video') }}</span>
												<span @click="onOk(scope.row)"
													class="border p-1 m-1 bg-[#eee] cursor-pointer text-title">{{
														$t('public.ok') }}</span>
											</template>


										</el-table-column>
									</el-table>
								</div>
							</div>
						</div>
					</template>
				</el-collapse-item>
				<!-- 远程运维 -->
				<el-collapse-item :name="3" class="info3 mt-4">
					<template #title>
						<div class="h-8 text-base pl-4 mt-2 font-semibold relative text-[#fafafa]">{{
							$t('machine.operations.operation') }}</div>
					</template>
					<template #default>
						<div class="grid grid-cols-3 gap-10">
							<div class="min-h-64 status_item p-3" v-for="(items, index) in elFormData.operationsList"
								:key="index">
								<h1 class="text-base font-bold">{{ items.title }}</h1>
								<div class="mt-2 w-full flex flex-wrap">
									<div class="w-1/2 leading-8 mt-3" v-for="(item, index) in items.list1" :key="index">
										<span class="cursor-pointer border p-2 rounded-md" @click="onTitle(item)">{{
											item.title }}</span>
									</div>
								</div>
							</div>
						</div>
					</template>
				</el-collapse-item>
			</el-collapse>
		</el-form>
		<!-- 远程设置 -->
		<el-dialog v-model="data.macstatus" :title="$t('machine.settings')" center width="40%">
			<el-form :model="data.infoMachine" :inline="true" label-width="120">

				<el-form-item :label="$t('machine.code') + ':'" prop="machine_id" class="w-10/12">
					<el-input v-model="data.infoMachine.machine_id" :placeholder="$t('message.pleaseEnter')" readonly />
				</el-form-item>

				<el-form-item :label="$t('machine.function') + ':'" prop="machine_id" class="w-10/12">
					<el-input v-model="data.title" :placeholder="$t('message.pleaseEnter')" readonly />
				</el-form-item>

				<el-form-item :label="$t('machine.executionTime') + ':'" prop="machine_id" class="w-10/12">
					<el-select v-model="data.time">
						<el-option :label="$t('machine.executeImmediately')" :value="1" />
						<el-option v-if="data.infoMachine.msgType <= 5" :label="$t('machine.timedExecution')"
							:value="2" />
					</el-select>
				</el-form-item>

				<el-form-item v-if="data.infoMachine.msgType == 6" :label="$t('machine.mchineVolume') + ':'"
					prop="machine_id" class="w-10/12">
					<el-slider v-model="data.infoMachine.volume" size="large" :step="10" show-stops />
				</el-form-item>

				<el-form-item v-if="data.infoMachine.msgType == 7" :label="$t('machine.lightBrightness') + ':'"
					prop="machine_id" class="w-10/12">
					<el-slider v-model="data.infoMachine.light" size="large" :step="10" show-stops />
				</el-form-item>

				<el-form-item v-if="data.time == 2" :label="$t('date.time') + ':'" prop="machine_id" class="w-10/12">
					<el-date-picker v-model="data.infoMachine.time_point" :disabled-date="disabledDate" type="datetime"
						:placeholder="$t('message.pleaseSelect')" format="YYYY/MM/DD HH:mm:ss" value-format="x"
						style="width: 100%;" />
				</el-form-item>

				<div class="w-full text-center">
					<div class="inline-block">

						<el-button type="primary" size="small" @click="submit()">
							<template #default>
								<span class="text-sm">{{ $t('public.save') }}</span>
							</template>
						</el-button>

						<el-button size="small" @click="data.macstatus = false">
							<template #default>
								<span class="text-sm">{{ $t('public.cancel') }}</span>
							</template>
						</el-button>
					</div>
				</div>

			</el-form>
		</el-dialog>
		<!-- 运维帮助 -->
		<el-dialog v-model="data.operationsHple" :title="$t('machine.operations.maintenanceHelp')" center width="30%">
			<div class="text-center p-3 border bg-[#f5dfdf] text-[#e71a1a]">
				<span>【{{ getPlevel.gettime(data.operationsHpleData.create_time, 3) }}】</span>
				<span>{{ $t('machine.operations.errorIs') }}【{{ data.operationsHpleData.errorCode }}】</span>
				<span>{{ data.operationsHpleData.remark }}</span>
			</div>
			<div class="p-3 border mt-5 bg-[#e1f3d8] text-[#67c23a] overflow-hidden ">
				<h1> {{ $t('machine.operations.guidancePlan') }}:</h1>
				<p class="text-left break-words"></p>
			</div>
			<div class="border p-3">
				<p v-if="data.hpleConenetData.content" v-html="data.hpleConenetData.content"></p>
				<p v-else class="text-center">{{ $t('public.unData') }}</p>
			</div>

		</el-dialog>
		<!-- 视频播放 -->
		<el-dialog v-model="previewShow" :title="$t('order.consume.viewVideo')" center width="700px" destroy-on-close
			@close="previewShow = false">
			<span style="position: absolute;top: 21px;left: 60%;font-size: 16px;cursor: pointer;color: #409eff;"
				@click="downloadVideo(previewMedia.video, 'my-video.mp4')">下载</span>
			<div>
				<Video v-if="previewMedia.video" :url="previewMedia.video" />
				<div v-else class="text-center"> {{ $t('public.unData') }}</div>
			</div>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import machinetop from '../../common/machine_top.vue';
import { useRoute } from "vue-router";
import getPlevel from '@/utils/level'
import { getmachineError, getconfirmHandle } from '@/api/machine-operations';
import { setmachineVolume, setmachineLight, sendMainControl, getmachineFind } from '@/api/machine';
import { getFinderror } from '@/api/system-err';
import { getOrderVideo } from '@/api/order';
import { ElMessage, ElMessageBox } from "element-plus";
const route = useRoute()

let elFormData = reactive({
	statusList: [
		{
			title: $t('machine.operations.mechanism'),
			value: 1,
			list: [],
		},
		{
			title: $t('machine.operations.Control'),
			value: 2,
			list: [],
		},
		{
			title: $t('machine.operations.computer'),
			value: 3,
			list: [],
		}
	],
	operationsList: [
		{
			title: $t('machine.operations.Control'),
			value: 1 - 1,
			list1: [
				{ title: $t('machine.light'), value: 7 },

			]
		},
		{
			title: $t('machine.operations.computer'),
			value: 2 - 1,
			list1: [
				{ title: $t('machine.dormancy'), value: 1 },
				{ title: $t('machine.Power'), value: 2 },
				{ title: $t('machine.reboot'), value: 3 },
				{ title: $t('machine.shutdown'), value: 4 },
				{ title: $t('machine.update'), value: 5 },
				{ title: $t('machine.volumeCon'), value: 6 },

			]
		},
		{
			title: $t('machine.hardwareControl'),
			value: 3 - 1,
			list1: [
				{ title: $t('machine.beltOpen'), value: 'conveyorBeltOpen' },
				{ title: $t('machine.beltClose'), value: 'conveyorBeltClose' },
				{ title: $t('machine.doorOpen'), value: 'boxDoorOpen' },
				{ title: $t('machine.doorClose'), value: 'boxDoorClose' },
				{ title: $t('machine.extendsOut'), value: 'recycleOut' },
				{ title: $t('machine.extendsBin'), value: 'recycleIntro' },
				{ title: $t('machine.beginnPick'), value: 'pickUpHeadInit' }
			]
		}
	]
})
let data = reactive({
	isOk: 0,
	operationsHpleData: {},
	hpleConenetData: {},
	operationsHple: false,
	macstatus: false, // 弹窗
	activeOperations: [1, 2, 3],
	mtloading: true, // 加载
	info: {}, // 设备主体信息
	title: '', // 标题
	time: 1, // 执行时间
	infoMachine: { // 
		machine_id: '',
		msgType: '',
		time_point: '',
		volume: '',
		light: ''
	},
	infoError: {
		machine_id: '',
		errorCode: '',
		create_time: '',
		page: 1,
		pageNum: 15
	}
})

const previewShow = ref(false);
const previewMedia = reactive({
	video: ''
})
const formatTime = (timestamp) => {
	return new Intl.DateTimeFormat('zh-CN', {
		timeZone: 'Asia/Shanghai',
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		hour12: false // 24小时制
	}).format(timestamp * 1000).replace(/[^0-9]/g, '');
};
// 下载查看视频
const previewVideo = async (time: string, me_id: number) => {
	let orderNo = 'door_open_' + formatTime(time)
	const res = await getOrderVideo(orderNo, 'getOpenDoor', me_id)
	if (!res.data.transaction_video) {
		ElMessage.info(res.msg)
		return
	} else {
		previewMedia.video = res.data.transaction_video
	}
	previewShow.value = true;
}
const downloadVideo = (videoUrl, fileName) => {
	fetch(videoUrl).then(res => res.blob()).then(blob => {
		const a = document.createElement('a');
		document.body.appendChild(a)
		a.style.display = 'none'
		const url = window.URL.createObjectURL(blob);
		a.href = url;
		a.download = '订单视频.mp4';
		a.click();
		document.body.removeChild(a)
		window.URL.revokeObjectURL(url);
	})
		.catch(console.error);
}
let onOk = (row) => {
	let pram = {
		me_id: row.me_id
	}
	let arr = elFormData.statusList.filter(item => {
		if (row.error_position == item.value) {
			return item.list
		}
	})
	arr.flatMap(item => {
		const index = item.list.indexOf(row);
		if (index !== -1) {
			item.list.splice(index, 1);
		}
	})
	getconfirmHandle(pram)
}
let onErrorCode = (row: any) => {
	data.operationsHpleData = row
	getFinderror({ error_code: row.errorCode }).then(res => {
		data.hpleConenetData = res.data ? res.data : res.msg
	}).catch(err => {
		ElMessage({
			message: err.msg,
			type: 'error'
		})
	})
	data.operationsHple = true
}
let getSingle = () => {
	if (route.query.l == undefined) {
		ElMessage({
			message: $t('message.invalidData'),
			type: 'error'
		})
		return
	}
	let query_obj = JSON.parse(decodeURI(route.query.l))
	data.activeName = query_obj.type || 'operations'
	data.mtloading = true
	getmachineFind({ m_id: query_obj.id.m_id }).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			data.info = res.data
			data.info.address = getaddress(data.info)
			data.info.onlinetime = getPlevel.gettime(data.info.last_online_time, 3)
		}
	}).catch(err => {
		data.mtloading = false
	})
}
getSingle()
let getErrorList = async () => {
	let rowMachine = JSON.parse(decodeURI(route.query.l))
	data.infoError.machine_id = rowMachine.id.machine_id
	await getmachineError(data.infoError).then(res => {
		if (res.state == 200) {
			let arr1 = res.data.data.filter(item => { return item.error_position == 1 })
			let arr2 = res.data.data.filter(item => { return item.error_position == 2 })
			let arr3 = res.data.data.filter(item => { return item.error_position == 3 })
			elFormData.statusList.forEach(item => {
				if (item.value == 1) {
					item.list = arr1
				}
				if (item.value == 2) {
					item.list = arr2
				}
				if (item.value == 3) {
					item.list = arr3
				}
			})
		}
	})
}
getErrorList()
// 限制日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now()
}

// 获取设备单条信息
let onTitle = (row) => {
	data.infoMachine.msgType = row.value
	data.infoMachine.machine_id = data.info.machine_id
	data.infoMachine.time_point = ''
	data.title = row.title
	data.time = 1
	data.macstatus = true
}
// 数据提交
let submit = () => {
	if (data.infoMachine.msgType <= 5 || typeof data.infoMachine.msgType == 'string') {
		// 1. 休眠：sleep, 2. 唤醒：wakeUp, 3. 重启：reboot, 4. 关机：shutdown, 5. 软件升级：update
		let info = {
			machine_id: data.infoMachine.machine_id,
			msgType: data.infoMachine.msgType,
		}
		if (data.time == 2) {
			if (data.infoMachine.time_point == '' || data.infoMachine.time_point == null) {
				ElMessage({
					message: $t('message.pleaseTime'),
					type: 'error'
				})
				return
			} else {
				info.time_point = getPlevel.gettime(data.infoMachine.time_point, 3)
			}
		}
		setControl(info)
	} else {
		let info = {
			machine_id: data.info.machine_id
		}
		// 音量、灯光
		if (data.infoMachine.msgType == 6) {
			info.volume = data.infoMachine.volume
			sound(info)
		} else {
			info.light = data.infoMachine.light
			light(info)
		}
	}

}

// 1. 休眠：sleep, 2. 唤醒：wakeUp, 3. 重启：reboot, 4. 关机：shutdown, 5. 软件升级：update
let setControl = (e) => {
	sendMainControl(e).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.setSuccess'),
				type: 'success'
			})
			data.macstatus = false
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}

// 音量
let sound = (e) => {
	setmachineVolume(e).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.setSuccess'),
				type: 'success'
			})
			data.macstatus = false
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}

// 灯光
let light = (e) => {
	setmachineLight(e).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.setSuccess'),
				type: 'success'
			})
			data.macstatus = false
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	})
}
</script>
<style lang="scss">
.el-dialog__body {
	padding: 0px 20px 10px 20px;
}

.status_item {
	border: 1px solid #eee;
}

.info1 .el-collapse-item__header {
	background: rgba(75, 141, 284, 0.8);
}

.info1 {
	.el-collapse-item__wrap {
		border: 1px solid rgba(75, 141, 284, 0.8);
	}
}

.info2 {
	.el-collapse-item__wrap {
		border: 1px solid rgba(255, 97, 3, 0.8);
		padding: 20px;

		.text-title {
			color: rgb(49, 139, 241);
		}
	}
}

.info3 {
	.el-collapse-item__wrap {
		border: 1px solid #f03a3a;
		padding: 20px;

		.text-title {
			color: rgb(49, 139, 241);
		}
	}
}

.info2 .el-collapse-item__header {
	background: rgba(255, 97, 3, 0.8);
}

.info3 .el-collapse-item__header {
	background: #f03a3a;
}

.el-collapse-item__content {
	padding-bottom: 0PX;
}
</style>